#!/usr/bin/env python
# coding: utf-8
import hashlib
import os
from django.conf.urls import url
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt

from .handlers import qiniucloud

Error_Not_Login = JsonResponse({'retcode': 302, 'msg': '未登录'})


def CheckUserIsParentForApiCaller(request, *args, **kwargs):
    if 'ut' not in request.session and not valid_tyid(request.GET.get('id', ''), request.GET.get('token', '')):
        return Error_Not_Login

    realCall = kwargs.pop('_viewFunc')
    return realCall(request, *args, **kwargs)


def valid_tyid(id, token):
    """
    valid the interface of id
    :return:True or False
    """
    before_valid = hashlib.md5((hashlib.md5(
        "".join((id, 'yjyx0571zg')).encode()).hexdigest() + 'zg0571yjyx').encode()).hexdigest().upper()
    if before_valid == token:
        return True
    else:
        return False


urlpatterns_api = []


def addPreCheck(urlpatterns, checkFunC):
    checkFunC = csrf_exempt(checkFunC)
    for pattern in urlpatterns:
        urlRegx = pattern[0]
        if type(urlRegx) != list:
            urlRegList = [urlRegx]
        else:
            urlRegList = urlRegx

        viewFunc = pattern[1]
        if len(pattern) == 2:
            for one in urlRegList:
                urlpatterns_api.append(url(one, checkFunC, {'_viewFunc': viewFunc}))

        elif len(pattern) == 3:
            otherPara = pattern[2]
            otherPara['_viewFunc'] = viewFunc
            for one in urlRegList:
                urlpatterns_api.append(url(one, checkFunC, otherPara))
        else:
            # print '!!unsupported url format : %s' % pattern
            os._exit(3)


urlpatterns_api_agrs = [
    (r'^$', qiniucloud.qiniu_handler.dispatch),
]

addPreCheck(urlpatterns_api_agrs, CheckUserIsParentForApiCaller)

urlpatterns = [
    # url(r'^official/$', news.handler.dispatch),
] + urlpatterns_api
